// pages/agency/index.js
var app = getApp();
import tool from "../../utils/tool.js";
Page({

  /**
   * 页面的初始数据
   */
  data: {
    goodsnum: [{
      num: 0
    }, {
      num: 0
    }, {
      num: 0
    }, {
      num: 0
    }],
    gooodlist: "",
    zonjia: 0,
    payData: [],
    aarr: [],
    userId: '',
    result: [],
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.data.userId = wx.getStorageSync('userId')
    //请求商品列表
    wx.request({
      url: app.globalData.url+'/zkxj/cart/queryGoodsListByUserId',
      data: {
        "userId": this.data.userId,
      },
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: (res) => {
        // console.log(res);
        this.setData({
          gooodlist: res.data.data,
        });
      },
    })
  },
  //计算总价
  onChanges(event) {
    console.log(event);
    this.setData({
      result: event.detail,
    });
    
   this.prcpic()
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },
  //空函数
  catchtap() {

  },

  // 计算价格
  prcpic(){
    let res = this.data.result
    console.log(res);
    let prcnum = 0
    var allarr = []
    for (let i = 0; i < res.length; i++) {
      console.log(parseInt(res[i]));
      console.log(this.data.gooodlist[parseInt(res[i])]);
      allarr.push(this.data.gooodlist[parseInt(res[i])])
    }
    console.log(allarr);
      for (let k = 0; k < allarr.length; k++) {
        prcnum += allarr[k].price * allarr[k].quantity
      }
       console.log(prcnum);
      this.setData({
        zonjia: prcnum
      })
  },
  handledetodelait(e) {
    const statet = e.currentTarget.dataset['state'] || 0

    wx.navigateTo({
      url: `/pages/gooddelait/index?id=${statet}`,
    })
  },
   handledelae: tool.throttle(function (e) {
    const goodid = e[0].currentTarget.dataset['index'] || 0
    const price = e[0].currentTarget.dataset['price'];
    const num = e[0].currentTarget.dataset['num'] - 1;
    //修改购物车数量
    wx.request({
      url: app.globalData.url+'/zkxj/cart/updateGoods',
      data: {
        "userId": this.data.userId,
        "goodId": goodid,
        "modifiedtime": "",
        "price": price,
        "quantity": num,
      },
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.data.code == 0) {
          //请求商品列表
          wx.request({
            url: app.globalData.url+'/zkxj/cart/queryGoodsListByUserId',
            data: {
              "userId": this.data.userId,
            },
            method: 'POST',
            header: {
              'content-type': 'application/json',
              'token': wx.getStorageSync('token')
            },
            success: (res) => {
              if(res.data.code==0){
                
                this.setData({
                  gooodlist: res.data.data,
                });
                  //计算价格
              this.prcpic()
              }
            },
          })
        
        }
      },
    })
  }),
  handledeadd: tool.throttle(function (e) {
    const goodid = e[0].currentTarget.dataset['index'] || 0
    const price = e[0].currentTarget.dataset['price'];
    const num = e[0].currentTarget.dataset['num'] + 1;
    //修改购物车数量
    wx.request({
      url: app.globalData.url+'/zkxj/cart/updateGoods',
      data: {
        "userId": this.data.userId,
        "goodId": goodid,
        "modifiedtime": "",
        "price": price,
        "quantity": num,
      },
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.data.code == 0) {
          //请求商品列表
          wx.request({
            url: app.globalData.url+'/zkxj/cart/queryGoodsListByUserId',
            data: {
              "userId": this.data.userId,
            },
            method: 'POST',
            header: {
              'content-type': 'application/json',
              'token': wx.getStorageSync('token')
            },
            success: (res) => {
              if(res.data.code==0){
                
                this.setData({
                  gooodlist: res.data.data,
                });
                  //计算价格
              this.prcpic()
              }
            },
          })
        
        }
      },
    })
    //  console.log(goodid,price,num);
    //判断当前选中商品是否被被选中
    // console.log(this.data.gooodlist); 
    //   console.log(goodid.toString());
    //   console.log(this.data.result);
    //     // js检查数组中是否包含某个元素
    //   var arr =this.data.result
    //   if(arr.indexOf(goodid.toString())==-1){
    //       //修改购物车数量
    // wx.request({
    //   url: app.globalData.url+'/zkxj/cart/updateGoods',
    //   data: {
    //     "userId": this.data.userId,
    //     "goodId": goodid,
    //     "modifiedtime": "",
    //     "price": price,
    //     "quantity": num,
    //   },
    //   method: 'POST',
    //   header: {
    //     'content-type': 'application/json',
    //     'token': wx.getStorageSync('token')
    //   },
    //   success: (res) => {
    //    if(res.data.code==0){
    //      //请求商品列表
    // wx.request({
    //   url: app.globalData.url+'/zkxj/cart/queryGoodsListByUserId',
    //   data: {
    //     "userId": this.data.userId,
    //   },
    //   method: 'POST',
    //   header: {
    //     'content-type': 'application/json',
    //     'token': wx.getStorageSync('token')
    //   },
    //   success: (res) => {
    //     this.setData({
    //       gooodlist: res.data.data,
    //     });
    //   },
    // })
    //    }
    //   },
    // })
    //   }else{
    //         console.log("存在,索引是：",arr.indexOf())
    
    // }

  }),
    handletobuy() {
    // console.log(this.data.gooodlist);
    // console.log(this.data.result);
    let res = this.data.result
    console.log(res);
    let prcnum = 0
    var allarr = []
    for (let i = 0; i < res.length; i++) {
      console.log(parseInt(res[i]));
      // console.log(this.data.gooodlist[parseInt(res[i])]);
      allarr.push(this.data.gooodlist[parseInt(res[i])])
    }
    console.log(allarr);
    //整理数据格式
   
    let result = [];//结果保存
    for (let i = 0; i < allarr.length; i++) {
      delete allarr[i].createtime;
      delete allarr[i].modifiedtime;
      delete allarr[i].unit;
      delete allarr[i].userId;
      delete allarr[i].id;
      allarr[i].oldpric=allarr[i].price
      allarr[i].goodId=allarr[i].goodId
      console.log(allarr[i].goodId);
      allarr[i].price=allarr[i].price
       //获取到list的第i个对象，修改后返回一个新对象，不修改原对象
       var resss = JSON.parse(JSON.stringify(allarr[i]).replace(/goodId/g, 'id').replace(/quantity/g, "num"));
       console.log(resss);
       result.push(resss)
      
      }
    console.log(result);
    var detailsData = JSON.stringify(result);
    detailsData = encodeURIComponent(detailsData);
    wx.navigateTo({
      url: `/pages/seaccounts/index?arr=${detailsData}&sum=${JSON.stringify(this.data.zonjia)}&type=3&upgradeLevel=0`
    })
    console.log(this.data.payData);
    // if (this.data.aarr.length) {
    //   console.log(this.data.aarr);
    //   var detailsData = JSON.stringify(this.data.aarr);
    //   detailsData = encodeURIComponent(detailsData);
    //   wx.navigateTo({
    //     url: `/pages/zdseepg/index?arr=${detailsData}&sum=${JSON.stringify(this.data.zonjia)}&type=4&upgradeLevel=0`
    //   })
    // } else {
    //   wx.showToast({
    //     title: '你还未选购商品',
    //     icon: 'error',
    //     duration: 1000,
    //     mask: true
    //   })
    // }
  },
  handletobuys(){
    wx.showToast({
          title: '你还未选购商品',
          icon: 'error',
          duration: 1000,
          mask: true
        })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})